package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.user.MerchantMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@Configuration("com.sky.mapper.user")
public class UserServiceImpl implements UserService {
    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //调用微信接口服务，获得当前微信用户的openid
        Map<String,String> map=new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
        String json=HttpClientUtil.doGet(WX_LOGIN,map);
        JSONObject jsonObject= JSON.parseObject(json);
        String openid=jsonObject.getString("openid");
        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if (openid==null){
            throw new LoginFailedException("用户为空！");
        }
        //判断当前用户是否为新用户
        User user =userMapper.queryPhone(openid);
        if (user==null){
            log.info("用户为新用户！");
            //如果是新用户，自动完成注册
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insertUser(user);
        }
        //生成jwt令牌
        Map<String,Object> claims=new HashMap<>();
        claims.put("userId",user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),claims);
        UserLoginVO userLogin =new UserLoginVO();
        userLogin.setId(user.getId());
        userLogin.setOpenid(user.getOpenid());
        userLogin.setToken(token);
        //计算配送费
        Merchant merchant = merchantMapper.selectById(1L);
        String merchantLocation = MapUtils.addressToLnglat(merchant.getShopAddress());
        BigDecimal delivoryCost = MapUtils.getDelivoryCost(merchantLocation, userLoginDTO.getLocation());
        //查询商家信息
        UserLoginVO userLoginVO= new UserLoginVO();
        userLoginVO.setOpenid(user.getOpenid());
        userLoginVO.setToken(token);
        userLoginVO.setShopName(merchant.getShopName());
        userLoginVO.setShopAddress(merchant.getShopAddress());
        userLoginVO.setShopTelephone(merchant.getShopTelephone());
        userLoginVO.setShopId(merchant.getId());
        userLoginVO.setDeliveryFee(delivoryCost);
        //返回这个用户对象
        return userLoginVO;
    }
}
